package com.beiwei.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.beiwei.auto.mode.Job;
import com.beiwei.auto.mode.Role;
import com.beiwei.auto.mode.User;
import com.beiwei.mode.VDepartment;
import com.beiwei.mode.VUser;
import com.beiwei.service.DepartmentService;
import com.beiwei.service.JobService;
import com.beiwei.service.RoleService;
import com.beiwei.service.UserService;

@Controller
@RequestMapping("/user")
public class UserHandler {

	@Autowired
	private UserService userService;
	@Autowired
	private JobService jobService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private RoleService roleService;

	/**
	 * 查询该公司所有用户
	 */
	@RequestMapping("/query")
	public String query(Model model) {
		Subject currentUser = SecurityUtils.getSubject();
		VUser user = (VUser) currentUser.getPrincipal();

		List<User> userList = null;
		try {
			userList = userService.findAllUser(user.getUserCompanyId());
		} catch (Exception e) {
			e.printStackTrace();
		}

		model.addAttribute("userList", userList);
		return "userList";
	}

	/**
	 * 根据用户id批量删除用户
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/deleteUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@RequiresPermissions("user:delete")
	@ResponseBody
	public String deleteUser(HttpServletRequest request) {
		String[] userIds = request.getParameterValues("delete_id");
		if (userIds == null || userIds.length == 0) {
			return "请勾选用户！";
		}
		List list = Arrays.asList(userIds);
		try {
			if (userService.deleteUserByUserids(list)) {
				return "success";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(userIds);
		return "删除失败";
	}

	/**
	 * 修改用户 执行query需要"user:update"权限
	 */
	@RequestMapping(value = "/edit/{userId}", method = RequestMethod.GET)
	@RequiresPermissions("user:update")
	public String edit(@PathVariable("userId") Integer userId, Model model) {

		User user = null;// 修改的用户信息
		Job job = null;// 用户的岗位
		List<VDepartment> vDepartments = null;// 所有部门
		List<Role> rolesList = null;// 所有角色
		try {
			user = userService.findUserByUserId(userId);
			job = jobService.findJobByJobId(user.getUserJobId());
			vDepartments = departmentService.findVDepartmentListByCompanyId(user.getUserCompanyId());
			rolesList = roleService.findAllRole();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Map<String, String> roles = new HashMap<String, String>();
		for (Role role : rolesList) {
			roles.put(role.getRoleId() + "", role.getRoleName());
		}

		VUser vUser = new VUser(user);
		model.addAttribute("user", vUser);
		model.addAttribute("job", job);
		model.addAttribute("vDepartments", vDepartments);
		model.addAttribute("roles", roles);
		return "editUser";
	}

	/**
	 * 修改用户后保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.PUT, produces = "application/json; charset=utf-8")
	@RequiresPermissions("user:update")
	@ResponseBody
	public String editSave(VUser user) {
		StringBuffer userRoleIds = new StringBuffer();
		if (user.getUserRoles() != null) {
			for (String s : user.getUserRoles()) {
				userRoleIds.append(s).append(",");
			}
		}
		userRoleIds = userRoleIds.append("1");// 用户所拥有的的身份
		user.setUserRoleIds(userRoleIds.toString());

		try {
			if (userService.saveUser(user)) {
				return "success";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "操作失败";
	}

	/**
	 * 添加用户
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	@RequiresPermissions("user:create")
	public String add(Model model) {
		Subject currentUser = SecurityUtils.getSubject();
		User user = (User) currentUser.getPrincipal();

		List<VDepartment> vDepartments = null;// 该公司所有部门
		List<Role> rolesList = null;// 所有角色
		try {
			vDepartments = departmentService.findVDepartmentListByCompanyId(user.getUserCompanyId());
			rolesList = roleService.findAllRole();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, String> roles = new HashMap<String, String>();
		for (Role role : rolesList) {
			roles.put(role.getRoleId() + "", role.getRoleName());
		}

		model.addAttribute("user", new VUser());
		model.addAttribute("vDepartments", vDepartments);
		model.addAttribute("job", new Job());
		model.addAttribute("roles", roles);

		return "editUser";
	}

	/**
	 * 添加用户保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@RequiresPermissions("user:create")
	@ResponseBody
	public String addSave(VUser user) {

		Subject subject = SecurityUtils.getSubject();
		User currentUser = (User) subject.getPrincipal();

		StringBuffer userRoleIds = new StringBuffer();
		if (user.getUserRoles() != null) {
			for (String s : user.getUserRoles()) {
				userRoleIds.append(s).append(",");
			}
		}
		userRoleIds = userRoleIds.append("1");// 用户所拥有的的身份
		user.setUserRoleIds(userRoleIds.toString());
		user.setUserCompanyId(currentUser.getUserCompanyId());

		try {
			// 判断用户usercode是否存在
			if (userService.findUserByUsercode(user.getUsercode()) != null) {
				return "该登录账号已经存在！";
			} else if (user.getUsercode() != null && !user.getUsercode().equals("") && userService.addUser(user)) {
				return "success";
			}
			return "添加失败！";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "操作失败";
	}

	/**
	 * 进入用户修改自己密码页面
	 */
	@RequestMapping("/updatepwd")
	public String updatepwd(Model model) {
		model.addAttribute("user", new User());
		return "updatepwd";
	}

	/**
	 * 保存用户修改自己密码（要求用户输入原来密码。）
	 */
	@RequestMapping(value = "/savepwd", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String savePassword(HttpServletRequest request, User user) {
		Subject subject = SecurityUtils.getSubject();
		VUser currentUser = (VUser) subject.getPrincipal();
		String pwd = "";// 用户输入密码
		String newPwd = request.getParameter("newPwd").trim();

		if (newPwd == null || newPwd.equals("") || newPwd.length() < 6) {
			return "密码不能为空并且长度为6——10";
		}

		try {
			// 获取用户输入密码的md5密文
			pwd = userService.getMd5HashPwd(user.getPassword(), currentUser.getSalt());
			if (!pwd.equals(currentUser.getPassword())) {
				return "密码错误！";
			}

			user.setPassword(newPwd);

			if (userService.updateUserPwd(user)) {
				return "success";
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "密码修改失败！";
	}

}
